define(["../common"], function() {

	var statusPath = g_shopDomain + "/order/statusDo/json";
	var delPath = g_shopDomain + "/order/delDo/json";
	var loadStatusEnumPath = g_shopDomain + "/order/listStatus/json";
	var rectifyPath = g_shopDomain + "/orderGoods/rectifyDo/json";
	var statuses = null; 
	loadStatus(function(result) {statuses = result;});
	
	var orders = {};
	
	// 初始化 start###############
	
	setTimeout(function() {
		var vars,orderId,orderGoodsId;
		
		$("[id^='orderParams_']").each(function(i, el) {
			vars = $(this).attr("id").split("_");
			orderId = vars[1];
			orders[orderId] = $.parseJSON($(this).html());
		});
		$("[id^='ogParams_']").each(function(i, el) {
			vars = $(this).attr("id").split("_");
			orderId = vars[1];
			orderGoodsId = vars[2];
			if (!orders[orderId].orderGoodses) {
				orders[orderId].orderGoodses = {};
			}
			orders[orderId].orderGoodses[orderGoodsId] = $.parseJSON($(this).html());
		});
		
		// 显示各订单状态
		showCtrls();
	});
	
	// 分页功能
	loadjs(["pagectrl"]);
	// 表单验证初始化
	loadjs(["validator"], function() {
		$("#rectifyForm").validator({
    		valid: rectityOrderGoods
    	});
	});
	
	// 初始化 end###############

	// 选项卡选中状态
	$("[id^='statusFilter_" + $("#statuses").val() + "']:last").addClass("selected");
	// 状态筛选
	$("[id^='statusFilter_']").click(function() {
		$("#statuses").val($(this).attr("id").split("_")[1]);
		$("#form").submit();
	});
	
	// 全选
	$("[name='selectAll']").click(function() {
		$("[name='orderIds']").prop("checked", $(this).prop("checked"));
		$("[name='selectAll']").prop("checked", $(this).prop("checked"));
	});

	// 订单每个操作按钮事件
	$("[its='e_o_ctrl']").on('click', "a", function() {
		var orderId = ($(this).closest("tr").attr("id").split("_"))[1];
		var params = $(this).attr("its").split("_");
		if (params[2]  === "s") {// 修改状态status
			upStatus(orderId, params[3]);
		} else if (params[2]  === "r") {// 打秤校正rectify
			intoScan(orderId, params[3]);
		} else if (params[2]  === "d") {// 删除del
			del(orderId);
		}
		return false;
	});

	// 扫描接收表单事件处理
	$(function() {

		// 条码表单清空规则,防止键盘输入
		var barCodeIndex = -1;
		$("#i_r_scanCode").keyup(function() {
			clearTimeout(barCodeIndex);
			barCodeIndex = setTimeout(function() {
				$("#i_r_scanCode").val("");
			}, 100);
		});
		
		// 扫描状态提示相关"打秤..."
		var points = ['', '.', '..', '...'];
	  	var pointNum = 1;
	  	var tipIndex = -1;
		$(document).on('active', "[its='tip_o_r_']", function() {
			var $tip = $(this);
	  		$tip.html("打秤" + points[pointNum]);
	    	clearInterval(tipIndex);
	    	tipIndex = setInterval(function() {
	    		pointNum++;
	    		if (pointNum >= points.length) {
	    			pointNum = 0;
	    		}
	    		$tip.html("打秤" + points[pointNum]);
	    	}, 500);
		});
		
		$(document).click(function(event) {
			$this = $(this); 
	    	if (!$(event.target).is("#i_r_scanCode,#bt_r_submit") 
	    		&& $(event.target).is("input,textarea,select")) {// 点击表单对象时，退出扫描状态
	    		
	    		showCtrls();
	    		
	    	} else if ($this.its("tip_o_r_").length > 0) { // 处于"打秤..."状态时,扫描接收表单获得焦点
	    		$("#i_r_scanCode").focus();
	    	}
	    });
	    
	    $(document).blur(function() {
	    	showCtrls();
	    });

	});	
	
	// 显示各订单操作按钮
	function showCtrls() {
	  $("[id^='o_']").each(function() {
		var orderId = $(this).attr("id").split("_")[1];
	  	// $ctrl status
	  	showCtrl($(this).its("e_o_ctrl"), orders[orderId].status);
	  });
	}

	function showCtrl($ctrl, status) {
		var html = '';
		if (status === undefined) {
			html += '<span its="tip_o_r_" style="font-size:20px;font-weight:bold;width: 60px;display: inline-block;text-align: left;">修正...</span><br><a its="bt_o_r_0">结束</a>';
		} else {
			status = parseInt(status);
			if (status === 0) {
	    		html += '<a its="bt_o_r_1" class="btn2">打秤</a><a its="bt_o_s_2">配送</a> | <a its="bt_o_s_1">取消</a>';
	    	} else if (status === 2) {
	    	    html += '<a its="bt_o_s_4" class="btn2">签收</a><a its="bt_o_s_6">拒签</a>';
	    	} else if (status === 4) {
	    	    html += '24小时后自动确认';
	    	} else if (status === 5) {
	    	    html += '<a its="bt_o_s_7" class="btn2">确认退货</a><a its="bt_o_s_">恢复</a>';
	    	} else if (status === 6) {
	    	    html += '<a its="bt_o_s_">恢复</a> | ';
	    	} 
	    	if (status === 1 || status === 3 || status === 6 || status === 7) {
	    		html += '<a its="bt_o_d">删除</a>';
	    	}
		}
		$ctrl.html(html);
		$ctrl.find("a").attr("href", "javascript:;");
	}

	// 进入修正状态
	function intoScan(orderId, type) {
		showCtrls();
		if (parseInt(type) !== 1) return;
		
		var $order = $("#o_" + orderId);
		var $ctrl = $order.its("e_o_ctrl");
		showCtrl($ctrl);// 显示"打秤..."提示
		$ctrl.its("tip_o_r_").trigger('active');// 激活"打秤..."提示动画
		
		$("#i_r_orderId").val(orderId);
		$("#i_r_scanCode").focus().val("");
	}

	// 打秤校正商品费用
	function rectityOrderGoods(form) {
		var barCode = $("#i_r_scanCode").val();
		$("#i_r_scanCode").val("");
	   	if(!$(form).showMsg("更新订单...", 'load', true)){
	  		$(document).showMsg("勿频繁操作！", 'error');
	  		return;
	  	}
	    	    		
	    var orderId = $("#i_r_orderId").val();
	    var code = parseInt(barCode);
	    var ogRealCost = 0;// 条码中计算出来的费用
	  	if (code > 2e12 && code < 27e11) {
	  		ogRealCost = code%1e6;
	  		ogRealCost = parseInt(ogRealCost/10)/100;
	  		barCode = barCode.substring(2, 7);// 简码
	  	} else {
	  		$(form).showMsg("非生鲜类商品不可打秤", 'error');
	  		return;
	  	}
	  	
	  	var partItemId =  orderId + "_" + barCode + "_";
	  	var $og = $("[id^='og_" + partItemId + "']");// orderGoods
	  	if ($og.length === 0) {
	  		$(form).showMsg("订单中无此商品", 'error');
	  		return;
	  	}
	  	var orderGoodsId = $og.attr("id").split("_")[3];
	    	
	    $og.fadeTo(null,0.1);
	    $.post(rectifyPath, {orderId: orderId, orderGoodsId: orderGoodsId, realCost: ogRealCost}, function(data) {
	    	$og.fadeTo(null,1);
	    	if (data.status !== 0) {
	    		$(form).showMsg(data.message, 'error');
	    		return;
	    	}
	    	$(form).showMsg();
	    	
	    	var $o = $("#o_" + orderId);// order
	    	
	    	// 计算购买量及费用
	    	var ogPreCost = parseFloat(orders[orderId].orderGoodses[orderGoodsId].realCost);
	    	var ogPrice = parseFloat(orders[orderId].orderGoodses[orderGoodsId].price);
	    	var oPreCost = parseFloat(orders[orderId].realCost);
	    	
	    	var ogRealCount = ogRealCost/ogPrice;
	    	var oRealCost = oPreCost - ogPreCost + ogRealCost;
	    	
	    	orders[orderId].orderGoodses[orderGoodsId].realCost = ogRealCost.toFixed(2);
	     	
	    	$og.its("t_og_realCount").html(ogRealCount.toFixed(2));// 刷新购买量
	    	$o.its("t_o_realCost").html(oRealCost.toFixed(2));// 刷新合计
	    });
	}

	// 更改状态
	function upStatus(orderId, status) {
		var $order = $("#o_" + orderId);
		var $ctrl = $order.its("e_o_ctrl");
		if ($ctrl.doing()) return; 
		
		if (parseInt(status) === 1) {
			loadjs(["msgbox"], function() {
				$.msgbox({
					id: "upStatus_" + orderId + "_" + status,
					type: 'confirm',
					content: "确定要取消订单吗？",
					title: "提示",
					onClose: function() {
						this.val()?upDo_():void(0);
					}
				});
			});
			
		} else {
			upDo_();
		}

		function upDo_() {
			$ctrl.showMsg("请稍候...", 'load', true);
			$ctrl.parent("tr").fadeTo(null,0.1);
			
			var statusName = null;
			if (statuses[status]) {
				statusName = statuses[status].name;
			}
			$.post(statusPath, {orderId: orderId, status:statusName}, function(data) {
				if (data.status !== 0) {
					$ctrl.showMsg(data.message, 'error');
					$ctrl.parent("tr").fadeTo('fast',1);
					return;
				}
				$ctrl.parent("tr").fadeTo('fast',0.1,function() {
					$ctrl.showMsg();
					showCtrl($ctrl, data.result.ordinal);
					orders[orderId].status = data.result.ordinal;
					$order.its("t_o_status").html(data.result.storeText);
					$(this).fadeTo(null,1);
				});
			});
			
		}
	}

	// 删除
	function del(orderId) {
		var $order = $("#o_" + orderId);
		// 即将删除的包括地址行和商品列表行
		var $destTr = $order.prev("tr").addBack();
		if ($destTr.doing()) return; 
		
		loadjs(["msgbox"], function() {
			$.msgbox({
				id: "del_" + orderId,
				type: 'confirm',
				content: "确定要删除订单吗？",
				title: "提示",
				onClose: function() {
					this.val()?delDo_():void(0);
				}
			});
		});
		
		function delDo_() {
			$destTr.showMsg("正在删除...", 'load', true);
			$destTr.fadeTo(null,0.1);
			
			$.post(delPath, {orderId: orderId}, function(data) {
				if (data.status !== 0) {
					$destTr.showMsg(data.message, 'error');
					$destTr.fadeTo('fast',1);
					return;
				}
				
				$destTr.fadeOut(function(){
					$(this).showMsg();
					$(this).remove();
					
				});
			});
		}
	}

	// 获取状态枚举(本地缓存)
	function loadStatus(callback) {
		if (!localStorage.orderStatusList) {
			$.post(loadStatusEnumPath, function(data) {
				localStorage.orderStatusList = data;
				var obj = $.parseJSON(data);
				if (callback) callback(obj.result);
			}, 'text');
		} else {
			var obj = $.parseJSON(localStorage.orderStatusList);
			if (callback) callback(obj.result);
		}
	}

	// 打印相关 start ######################################
	
	
	//事件： 打印订单
	$("#printBt").click(function() {
		printOrder($(this), 0);
	});


	//事件： 打印捡物小票
	$("#printPickBt").click(function() {
		printOrder($(this), 1);
	});

	// 小票打印
	function printOrder($el, type) {
		var $checkboxs = $(":checkbox[name='orderIds']:checked");
		if ($checkboxs.size() === 0) {
			$el.showMsg("请选择要打印的订单", 'error');
			return;
		}
		var fw = $("#printframe").get(0).contentWindow;// frame window
		if (type === 0) {
			fw.printOrder();
		} else {
			fw.printPick();
		}
		fw.focus();// (ie兼容)不加则始终打印顶层页面
		fw.print();
	}
});
